#!/usr/bin/env python
# -*- coding: utf-8 -*-

import uuid
import platform
import ConfigParser
import logging
import os
import hashlib
from datetime import timedelta

import smvn.config as cfg

def get_mac_address():
    node = uuid.getnode()
    mac = uuid.UUID(int = node).hex[-12:]
    return mac        

def config_parser():
    config = ConfigParser.RawConfigParser()
    config.read(cfg.default_cfg)
    try:
        ret = config.get('info', 'repo')
        if ret == "":
            ret = cfg.default_repo
    except Exception, e:
        ret = cfg.default_repo
    return ret

def read_rec(name):
    c = ConfigParser.RawConfigParser()
    ret = 'proj/bdef'
    with open(cfg.default_rec) as recfile:  
        c.readfp(recfile)
        ret = c.get('DEFAULT', name)
    return ret

def write_rec(name, value):
    c = ConfigParser.RawConfigParser()
    c.read(cfg.default_rec)
    #c.add_section('rec')
    c.set('DEFAULT', name, value)
    with open(cfg.default_rec, 'w+') as recfile:
        c.write(recfile)

def get_default_compilerid():
    if platform.system()=='Windows':
        compilerid = 'MSVC15.0'
    else:
        compilerid = 'GNU4.8'

    return compilerid

def check_buildinfo():
    #global cfg.default_compiler_id
    #global cfg.default_lib_path
    compilerid = get_default_compilerid()
    if (os.path.exists(cfg.default_buildinfo_name)):
        with open(cfg.default_buildinfo_name) as bf:
            build_info = bf.read()
            if (build_info):
                cfg.default_lib_path = build_info.strip()
                compilerid = build_info.split('-')[-1].strip()
                cfg.default_compiler_id = compilerid


    cfg.default_lib_path = '%s-%s-%s'%(platform.system(), platform.machine(), compilerid)

    #bin_str = platform.machine()+'-'+compilerid
    bin_str = compilerid
    if compilerid.startswith('MSVC'):
        cfg.default_bin_path = pjoin(cfg.default_bin_prefix, bin_str, 'Debug')
    else:
        cfg.default_bin_path = pjoin(cfg.default_bin_prefix, bin_str)

def make_grouppath(group):
    """
     make a group path with group ID
    """
    p = group.split('.')
    return '/'.join(p)

def merge_map(dmap, dirname, ver):
    try:
        old_ver = dmap[dirname] 
        if (old_ver!= ver):
            logging.error("Dependenci conflict! %s vs %s", old_ver, ver)
            sys.exit(-1)
    except KeyError:
        dmap[dirname] = ver

def merge_maps(dst, src):
    if src is not None:
        for k, v in src.items():
            merge_map(dst, k, v)

def get_file_type(fext):            
    if (fext == '.lib' or fext == '.a'):
        return '.lib'
    elif (fext == '.h' or fext == '.hpp'):
        return '.h'
    else:
        return fext

def pjoin(*args):
    elems = [e.strip().rstrip('/\\') for e in args if e != '']
    if len(elems) == 1:
        return elems[0]
    else:
        nel = [e.lstrip('/\\') for e in elems[1:]]
        ret = '%s/%s'%(elems[0], '/'.join(nel))
    return ret

def get_md5str(filename):
    """
     @brief get_md5str get md5 str from filename
    """
    return open(filename).read()

def cal_md5(filename):
    """
     @brief cal_md5 calculate md5 checksum for a file
    """
    m = hashlib.md5()
    m.update(open(filename, 'rb').read())
    return m.hexdigest()

def write_md5(filename, hexmd=None):
    """
     @brief write_md5 write md5 to a filename.md5 file
    """
    if hexmd is None:
        hexmd = cal_md5(filename)
    with open(filename+'.md5', 'w') as nf:
        nf.write(hexmd)
    return hexmd

def is_same_file(filename, fulldstname):
    """
     @brief is_same_file 首先判断修改大小，再判断修改时间，若都一致，初步判断一致
    """
    ret = False
    if os.path.exists(fulldstname): 
        curstat = os.stat(filename)
        oldstat = os.stat(fulldstname)
        if (curstat.st_size == oldstat.st_size
            and int(curstat.st_mtime*1000) == int(oldstat.st_mtime*1000)
           ):
            ret = True
    return ret

FMTSTR='%s%30s | '
def print_map(m, extra="", fmtstr=FMTSTR):
    for k in m:
        print(fmtstr%(extra, k), m[k])
